const http = require("http");
const fs = require("fs");
const path = require("path");

http.createServer((req,res)=>{
    var str = "";
    req.on("data",(chunk)=>{
        str += chunk;
    })
    req.on("end",()=>{
        var  obj = JSON.parse(str);
        var filePath = path.join(__dirname,"./data.json");
        fs.readFile(filePath,(err,data)=>{
            if(err){
                console.log(err);
            }else{
                var userlist = JSON.parse(data.toString("utf8")).userList;
                var i=0;
                for(; i<userlist.length; i++){
                    if(obj.userName===userlist[i].userName){
                        if(obj.pwd===userlist[i].pwd){
                            console.log("登录成功")
                        }else{
                            console.log("密码错误")
                        }
                        break;
                    }
                }
                if(i==userlist.length){
                    console.log("该用户不存在,是否添加新用户？（Y/N）");
                    var tip = process.argv[2];
                    if(tip==="Y"){
                        userlist.push(obj);
                        var listObj = {userList:userlist}
                        var listStr = JSON.stringify(listObj);
                        fs.writeFile(filePath,listStr,function(err){
                            if(err){
                                console.log(err);
                            }
                        })
                    }
                }
            }
        })
    })
}).listen(8081)